Python Strings

"str" is a built-in string class in python.

String literals can be enclosed by either double or single quotes.

Single quotes are commonly used.

Backslash escapes work the usual way within both single and double quoted literals, e.g. \n \' \".

A double quoted string literal can contain single quotes without any fuss, e.g., " I didn't do it") and likewise single quoted string can contain double quotes.

A string literal can span multiple lines, but there must be a backslash at the end of each line to escape the newline.

String literals inside triple quotes, """ or ```, can span multiple lines of text.

Python strings are immutable, which means they can not be changed after they are created.

*new* strings can be used to represent computed values.

For example, the expression (`hello'+ `there') takes in the 2 strings `hello' and `there' and builds a new string `hellothere'.

Characters in a string can be accessed using the standard[] syntax.

Python uses zero-based indexing, and if s is `hello', s[1] is e.

If the index is out of bounds for the string, Python raises an error.

The Python style is to halt if it can not tell what to do, rather than just make up a default value.

s=`hi'
print s[1]     ## i
print len(s)   ## 2
print s+` there'  ## hi there

Code block 1

Code block 1 shows the illustrative python code.

The len(string) function returns the length of a string.

The `+' operator can concatenate two strings.

The str() function converts values to a string form, so that they can be combined with other strings.

pi=3.14
## text = `The value of pi is '+pi   ## error
text=`The value of pi is '+str(pi)   ## correct

Code block 2

Code block 2 shows the illustrative example.

[0]

https://developers.google.com/edu/python/strings

results matching ""

    No results matching ""